<?php
session_start();

if(!isset($_SESSION['session_key'])):

    if(isset($_POST['Email']) && isset($_POST['Password'])):
        global $db;

        $email = mysqli_real_escape_string($db,$_POST['Email']);
        $password = md5($_POST['Password']);

        $query = 'SELECT ID, Level FROM USERS WHERE `Email`="'.$email.'" AND `Password`="'.$password.'"';
        $result = $db->query($query);
        $isUser = $result->num_rows;
        if($isUser){
            $user = $result->fetch_assoc();
            $_SESSION['session_key'] = $user['ID'];

            header('Location: ../user-profile.php'); 
        }
        header('Location: ../signup.php?status=failed');
    endif;

else:
    $user = $_SESSION['session_key'];
    global $db;

    $query = 'SELECT Level FROM USERS WHERE `ID`='.$user;
    $result = $db->query($query); 
    $isUser = $result->num_rows;
    if($isUser){
        $user = $result->fetch_assoc();
            header('Location: ../user-profile.php');
    }
    else{
         header('Location: ../signup.php?status=failed');
    }

endif;

?>